import ffmpeg from 'fluent-ffmpeg';
import path from 'path';
import fs from 'fs';
import figlet from 'figlet';


/**
 * 获取当前文件目录
 * @returns 目录
 */
function dirname() {
  const url = new URL(import.meta.url);
  return url.pathname.substring(0, url.pathname.lastIndexOf('/'));
}


/**
 * 视频转图片
 * 
 * @param {视频路径} video 
 * @param {输出路径} output 
 * @param {格式:gif or webp} format 
 * @param {开始时间 时:分:秒} startTime 
 * @param {截取秒数 秒} duration 
 */
async function video2gif(video, output, format = 'gif', startTime = '00:00:00', duration = 10) {
  if (!fs.existsSync(video)) {
    console.error('视频文件不存在!');
    return;
  }
  
  return new Promise((resolve, reject) => {
    ffmpeg(video)
    .setStartTime(startTime)
    .setDuration(duration)
    .format(format)
    .outputOptions('-vf', 'fps=10,scale=320:-1')
    .output(output)
    .on('end', () => resolve())
    .on('error', (err) => reject(err))
    .run();
  });
}

/**
 * 
 * @param {文件路径} video 
 * @param {图片格式} format 
 */
function newGifName(video, format) {
  const filename = `${path.basename(video)}.${format}`;
  return `${path.join(dirname(), 'output', filename)}`;
}

/**
 * 欢迎语
 * @param {欢迎语} msg 
 */
function welcome(msg) {
  const data = figlet.textSync(msg, {
    font: 'big',
    horizontalLayout: 'default',
    verticalLayout: 'default'
  });
  console.log(data);
}

export {
  video2gif, welcome, newGifName
};